package com.zuche.seraph.core;

import com.zuche.seraph.common.configuration.Conf;
import com.zuche.seraph.common.configuration.DynamicConfigLoader;
import com.zuche.seraph.common.utils.ServerManager;
import com.zuche.seraph.core.agent.AgentConnectionStore;
import com.zuche.seraph.core.agent.NettyServerForAgent;
import com.zuche.seraph.core.agent.handle.AgentMessageHandler;
import com.zuche.seraph.core.agent.handle.AgentMessageProcessor;
import com.zuche.seraph.core.intf.SessionManager;
import com.zuche.seraph.core.ui.NettyServerForUi;
import com.zuche.seraph.core.ui.UiConnectionStore;
import com.zuche.seraph.core.ui.command.CommunicateCommandStore;
import com.zuche.seraph.system.service.AppService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;

@Component
public class NettyServerManager {

    private static final Logger logger = LoggerFactory.getLogger(NettyServerManager.class);

//    @Autowired
//    private RegistryStore registryStore;

    @Autowired
    private CommunicateCommandStore commandStore;

    @Autowired
    private UiConnectionStore uiConnectionStore;

    @Autowired
    private AgentConnectionStore agentConnectionStore;

    @Autowired
    private SessionManager sessionManager;

    @Autowired
    private AppService appService;

    @Autowired
    private List<AgentMessageProcessor> agentMessageProcessors;

    private volatile String uiNode;
    private Conf conf;

    int websocketPort = -1;
    int tomcatPort = -1;

    private NettyServerForAgent nettyServerForAgent;

    private NettyServerForUi nettyServerForUi;


    @PostConstruct
    public void start() {
        conf = Conf.fromMap(DynamicConfigLoader.load("global.properties").asMap());
        websocketPort = conf.getInt("server.port", -1);
        tomcatPort = ServerManager.getTomcatPort();
        nettyServerForAgent = startAgentServer(conf);
        nettyServerForUi = startUiServer(conf);
        online();
    }


    @PreDestroy
    public void stop() {
        offline();
        nettyServerForUi.stop();
        nettyServerForAgent.stop();
    }


    private void online() {

    }

    private void offline() {
        
    }


    private NettyServerForUi startUiServer(Conf conf) {
        NettyServerForUi serverForUi = new NettyServerForUi(conf, commandStore, uiConnectionStore, agentConnectionStore, sessionManager, appService);
        serverForUi.start();
        return serverForUi;
    }

    private NettyServerForAgent startAgentServer(Conf conf) {
        AgentMessageHandler handler = new AgentMessageHandler(agentMessageProcessors);
        NettyServerForAgent serverForAgent = new NettyServerForAgent(conf, handler);
        serverForAgent.start();
        return serverForAgent;
    }


}
